import { useEffect, useState } from 'react'
import { Card, Row, Col, List, Tag } from 'antd'
import { useNavigate } from 'react-router-dom'
import { courseService } from '../../services'

const MyCourses = () => {
  const navigate = useNavigate()
  const [enrollments, setEnrollments] = useState([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    loadMyCourses()
  }, [])

  const loadMyCourses = async () => {
    try {
      setLoading(true)
      const response: any = await courseService.getEnrolledCourses()
      if (response.code === 200) {
        setEnrollments(response.data)
      }
    } catch (error) {
      console.error('Load my courses error:', error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ maxWidth: '1200px', margin: '0 auto', padding: '24px' }}>
      <h1>我的课程</h1>
      <List
        grid={{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4 }}
        loading={loading}
        dataSource={enrollments}
        renderItem={(enrollment: any) => (
          <List.Item>
            <Card
              hoverable
              cover={
                <div style={{
                  height: '160px',
                  background: '#f0f2f5',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}>
                  {enrollment.course.cover ? (
                    <img 
                      src={enrollment.course.cover} 
                      alt={enrollment.course.title} 
                      style={{ width: '100%', height: '100%', objectFit: 'cover' }} 
                    />
                  ) : (
                    <span>课程封面</span>
                  )}
                </div>
              }
              onClick={() => navigate(`/courses/${enrollment.course.id}/learn`)}
            >
              <Card.Meta
                title={enrollment.course.title}
                description={
                  <div>
                    <div>进度: {enrollment.progress}%</div>
                    {enrollment.completedAt && (
                      <Tag color="success">已完成</Tag>
                    )}
                  </div>
                }
              />
            </Card>
          </List.Item>
        )}
      />
    </div>
  )
}

export default MyCourses
